/*
 * Amadeus Confidential Information:
 * Unauthorized use and disclosure strictly forbidden.
 * @1998-2009 - Amadeus s.a.s - All Rights Reserved.
 */
package com.amadeus.spin.standard.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public abstract class SoapShooterUtils {

  /**
   * Generates a Zip file from a list of files on.
   *
   * @param fileList
   *          list of String containing the full path of the files to put into
   *          the zip
   *
   * @param zipFullName
   *          full name of the zip to create
   *
   * @return true if zip correctly created
   */
  public static String generateZipFileFromFileList(List<String> fileList, String zipFullName) {
    StringBuffer zipLogs = new StringBuffer();
    try {
      FileOutputStream fileOutputStream = new FileOutputStream(zipFullName);
      ZipOutputStream zip = new ZipOutputStream(fileOutputStream);
      InputStream is = null;
      for (int i = 0; i < fileList.size(); i++) {
        String curPath = fileList.get(i);
        File file = new File(curPath);
        try {
          int dataBlock;
          byte[] buffer = new byte[4096];
          is = new FileInputStream(file);
          zip.putNextEntry(new ZipEntry(curPath));
          while ((dataBlock = is.read(buffer)) != -1) {
            zip.write(buffer, 0, dataBlock);
          }
        }
        catch (IOException e) {
          zipLogs.append("Cannot access " + curPath + "\n");
        }
        finally {
          if (is != null) {
            is.close();
          }
        }
      }
      try {
        fileOutputStream.close();
        zip.closeEntry();
        zip.close();
      }
      catch (IOException e) {
        zipLogs.append("Cannot close " + zipFullName + "\n");
        // can occur when the zip file is empty
        return zipLogs.toString();
      }
    }
    catch (IOException e) {
      zipLogs.append("Error occured while trying to create " + zipFullName + "\n");
      return zipLogs.toString();
    }
    return zipLogs.toString();
  }
}
